#include "portal_md5.h"
#include "portal_nas.h"

IPADDRTYPE portal_find_acip_by_md5(uchar *digest)
{
    struct portal_acip_s *ac_ip;

    list_for_each_entry(ac_ip, &portal_args.acip_lst, lst, struct portal_acip_s) {
        if (!memcmp(ac_ip->md5, digest, strlen(ac_ip->md5))) {
            return ac_ip->acip;
        }
    }

    return 0;
}

IPADDRTYPE portal_find_acip_by_name(char *acname)
{
    struct portal_acip_s *ac_ip;

    list_for_each_entry(ac_ip, &portal_args.acip_lst, lst, struct portal_acip_s) {
        if (!strcmp(acname, ac_ip->acname)) {
            return ac_ip->acip;
        }
    }

    return 0;
}

bool portal_find_acip_by_ip(IPADDRTYPE acip)
{
    struct portal_acip_s *ac_ip;

    list_for_each_entry(ac_ip, &portal_args.acip_lst, lst, struct portal_acip_s) {
        if (acip == ac_ip->acip) {
            return TRUE;
        }
    }

    return FALSE;
}

void portal_make_acip_md5()
{
    struct portal_acip_s *ac_ip;
    char *ip_buf, md5[16] = {0}, tmp[253];
    struct in_addr ip;

    list_for_each_entry(ac_ip, &portal_args.acip_lst, lst, struct portal_acip_s) {
        ip.s_addr = ac_ip->acip;
        ip_buf = inet_ntoa(ip);
        snprintf(tmp, sizeof(tmp), "%s%s", portal_args.key, ip_buf);
        portal_md5(tmp, strlen(tmp), md5);
        portal_hex_to_str((uchar *)md5, 16, ac_ip->md5);
    }
}

bool portal_add_acip(char *acname, IPADDRTYPE acip)
{
    struct portal_acip_s *ac_ip;

    list_for_each_entry(ac_ip, &portal_args.acip_lst, lst, struct portal_acip_s) {
        if (acip == ac_ip->acip
                && (acname == NULL ? ac_ip->acname[0] == '\0' : !strcmp(acname, ac_ip->acname))) {
            return TRUE;
        }
    }

    ac_ip = malloc(sizeof(*ac_ip));
    if (!ac_ip) {
        return FALSE;
    }

    memset(ac_ip, 0, sizeof(*ac_ip));
    if (acname) {
        strncpy(ac_ip->acname, acname, sizeof(ac_ip->acname));
    }
    memcpy(&ac_ip->acip, &acip, sizeof(IPADDRTYPE));
    list_add_tail(&ac_ip->lst, &portal_args.acip_lst);

    return TRUE;
}

